package com.cetccloud.ap.proxy.channel.cossDomain.s30.channel.send;

import com.cetccloud.ap.proxy.channel.cossDomain.s30.handler.recv.RecvChannelHandler;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.handler.recv.RecvHandlerHolder;
import com.sun.jna.NativeLong;
import com.sun.jna.ptr.PointerByReference;
import com.thunisoft.exchange.gateway.protocol.GatewayProtocol;
import com.thunisoft.exchange.gateway.protocol.channel.GatewayChannelMessage;
import com.thunisoft.exchange.gateway.protocol.channel.GatewayChannelMessageType;
import com.wish.xsagent.JXSAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName Recv4SendHandle
 * @Description
 * @Author superz
 * @Date 2021/4/23 10:08
 * @Version 1.0
 **/
@Slf4j
@Component
public class Recv4SendHandle implements JXSAgent.recv_func_ptr {

    @Autowired
    private RecvHandlerHolder recvHandlerHolder;

    @Override
    public void invoke(String msg, boolean result, PointerByReference data, NativeLong len) {
        log.info("### Recv4SendHandle result: {}, msg: {} ", result, msg);
//        log.info("+++++++++++ callback data byte length := " + len);
//        new String(data.getPointer().getByteArray(0, len.intValue()), StandardCharsets.ISO_8859_1);

        byte[] bytes = data.getPointer().getByteArray(0, len.intValue());

        try {
            // 按现在的设计，只会处理: GatewayChannelMessageType.response
            GatewayChannelMessage channelMessage = GatewayProtocol.decodeChannelMessage(bytes);
            GatewayChannelMessageType messageType = channelMessage.type();
            RecvChannelHandler handler = recvHandlerHolder.getChannelHandler(messageType);
            if (null == handler) {
                log.error("Recv4SendHandle 不支持的messageType: " + messageType);
                return;
            }
            handler.handle(channelMessage);
        } catch (Exception e) {
            log.error("Recv4SendHandle invoke error", e);
        }
    }
}
